<template>
  <div class="container">
    <hy-nav-bar :title="'个人信息'" v-if="!configStore.isWeChatBrowser"></hy-nav-bar>
    <u-cell-group>
      <u-cell-item title="头像" hover-class="cell-hover-class" :icon-style="{
        'color': '#B0B0B0'
      }">
        <!-- #ifdef H5 -->
        <u-avatar :src="getImgFullPath(userInfo.avatar)" mode="square"></u-avatar>
        <button class="customBtn" @click="onChooseImage"></button>

        <!-- #endif -->
        <!-- #ifdef MP-WEIXIN -->
        <u-avatar :src="getImgFullPath(userInfo.avatar)" v-if="userInfo.avatar"></u-avatar>
        <view v-else class="avatar">
          <open-data type="userAvatarUrl"></open-data>
        </view>
        <button class="customBtn" open-type="chooseAvatar" @chooseavatar="onChooseAvatar"></button>
        <!-- #endif -->
      </u-cell-item>
      <u-cell-item title="昵称" hover-class="cell-hover-class" @click="toUpdateNickname">
        {{ userInfo.nickname }}
      </u-cell-item>
    </u-cell-group>
    <view class="sync" v-if="configStore.isWeChatBrowser"><text @click="syncWxInfo">同步微信头像和昵称</text> <u-icon
        name='reload'></u-icon>
    </view>
    <hy-image-cropper :src="avatarTempUrl" @cancel="cutCancel" @confirm="cutConfirm"></hy-image-cropper>
    <view class="gap"></view>
    <u-cell-group>
      <u-cell-item :arrow="false" title="推荐码" hover-class="cell-hover-class" @click="copyFn">
        <template v-slot:right-icon>
          <text>{{ shareCode }}</text>
        </template>
      </u-cell-item>
    </u-cell-group>
    <u-cell-group>
      <u-cell-item :arrow="false" title="二维码名片" hover-class="cell-hover-class">
        <template v-slot:right-icon>
          <u-icon :name="ic_qrcode" size="30" color="#409EFF" style="margin-right: 10rpx"></u-icon>
          <u-icon name="arrow-right" size="24" color="#B0B0B0"></u-icon>
        </template>
      </u-cell-item>
    </u-cell-group>
    <view class="gap"></view>
    <u-cell-group>
      <u-cell-item title="我的地址" hover-class="cell-hover-class"
        @click="goUrlFn(`/packageB/pages/addressList/index?type=mine&id=''`)">
      </u-cell-item>
      <!-- <u-cell-item title="修改密码" hover-class="cell-hover-class" @click="goUrlFn(`/packageB/pages/resetPassword/index`)">
      </u-cell-item> -->
      <!-- <u-cell-item
        title="邀请好友"
        hover-class="cell-hover-class"
        @click="
          goUrlFn(`/packageB/pages/invited/index`)
        "
      >
      </u-cell-item> -->
    </u-cell-group>
  </div>
</template>
<script setup lang="ts">
import { reactive, ref } from 'vue'
import { onLoad, onShow, onReady } from '@dcloudio/uni-app'
import { storeToRefs } from 'pinia'
import { baseApi, productApi, userApi } from '@/api'
import { getImgFullPath } from '@/utils/index'
import { upload } from '@/common/ali-oss'
import { useUserStore, useConfigStore } from '@/store'
import { copyContent } from '@/utils';
import {
  isWeChat,
  base64ToFile,
  imageUrlToFile,
  wxUploadImage,
  route
} from '@/utils/common'
import ic_qrcode from '@/static/ic_qrcode.png'


const userStore = useUserStore()
const configStore = useConfigStore()
const shareCode = uni.getStorageSync('userInfo')?.shareCode || ''
const { userInfo } = storeToRefs(userStore)
function goUrlFn(url: any) {
  if (userStore.checkLoginState()) {
    if (url) {
      uni.navigateTo({
        url
      })
    }
  }
}
async function onChooseAvatar(e: { detail: { avatarUrl: any } }) {
  const { avatarUrl } = e.detail
  userInfo.value.avatar = avatarUrl
  avatarTempUrl.value = avatarUrl
}
const avatarTempUrl = ref('')
function onChooseImage() {
  uni.chooseImage({
    count: 1,
    success(res) {
      avatarTempUrl.value = res.tempFiles[0].path
      // res.tempFiles[0]
    }
  })
}
function uploadImage(file: any) {
  upload({
    file,
    onSuccess: async (ret: { url: any }) => {
      successFn(ret.url)
    },
    onError() {
      uni.showToast({
        title: '上传失败'
      })
    }
  })
}

async function cutConfirm(e: any) {
  // #ifdef H5
  const file = base64ToFile(e.detail.tempFilePath, `${new Date()}`)
  uploadImage(file)
  // #endif
  // #ifdef MP-WEIXIN
  const res = await wxUploadImage(e.detail.tempFilePath)
  successFn(res?.data)
  // #endif
}
function cutCancel() {
  avatarTempUrl.value = ''
}
async function successFn(url: any) {
  await userApi.userInfoUpdate({
    avatar: url
  })
  await userStore.getUserInfo()
}
async function updateNickname(e: { detail: { value: any } }) {
  uni.showLoading({ title: '修改中' })
  await userApi.userInfoUpdate({
    nickname: e.detail.value
  }).finally(() => {
    uni.hideLoading()
  })
  await userStore.getUserInfo()
}
function copyFn() {
  copyContent(shareCode)
}
function toUpdateNickname() {
  route({
    url: '/packageD/pages/profile/updateNickname',
  })
}
function syncWxInfo() {
  uni.showModal({
    title: '提示',
    content: '确认更新为当前微信的头像和昵称？',
    showCancel: true,
    success: async ({ confirm, cancel }) => {
      if (confirm) {
        const params = {
          nickname: userStore.userInfo?.phone?.toString().replace(/(\d{3})\d{4}(\d{4})/, '$1****$2'),
          avatar: userStore.userInfo?.avatar
        }
        if (userStore.wxUserInfoGetter?.headimgurl) {
          params.avatar = userStore.wxUserInfoGetter?.headimgurl
        }
        if (userStore.wxUserInfoGetter?.nickname) {
          params.nickname = userStore.wxUserInfoGetter?.nickname
        }
        uni.showLoading({
          title: "用户信息更新中"
        })
        await userApi.userInfoUpdate(params).finally(() => {
          uni.hideLoading()
        })
        await userStore.getUserInfo()
      }
    }
  })
}
onLoad((option) => { })
</script>


<style lang="scss" scoped>
.container {
  min-height: 100vh;
  background-color: #f7f7f7;

  .sync {
    text-align: right;
    margin: 20rpx 30rpx 40rpx 0;
    font-size: 24rpx;
    color: #FF6C18;
  }

  .avatar {
    width: 120rpx;
    height: 120rpx;
    border-radius: 50%;
    display: inline-block;
    overflow: hidden;
  }

  .gap {
    margin-bottom: 20rpx;
  }

  .customBtn {
    padding: 0;
    border: 0;
    background-color: inherit;
    position: absolute;
    top: 0;
    right: 0;
    width: 200rpx;
    height: 100%;
    z-index: 1;
    opacity: 0;

    &:after {
      border: none;
    }
  }

  :deep(.uicon-arrow-right) {
    &:before {
      font-size: 26rpx;
    }

    color: #B0B0B0;
  }
}
</style>
